package com.rupertjones.globalcron.web;

import com.rupertjones.globalcron.web.model.DisplayableJob;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;


/**
 * <p>&copy Rupert Jones 2011</p>
 *
 * @author rup
 */
public class InfoJobAction extends AbstractAction {

    private DisplayableJob job;

    @Before(stages = LifecycleStage.BindingAndValidation)
    public void loadAndBind() {
        String id = getContext().getRequest().getParameter("job.id");
        int jobId = Integer.parseInt(id);
        job = getJobService().getDisplayableJob(jobId);
    }

    public boolean isRunningJob() {
        return getJobService().hasEnabledJob(job.getId());
    }

    public DisplayableJob getJob() {
        return job;
    }

    @HandlesEvent(value = "run")
    public Resolution runNow() {
        getJobService().runNow(job.getJobDescriptor());
        return view();
    }

    public boolean isLocal() {
        String hostname = job.getHostname();
        return hostname != null && hostname.equals(getCurrentHost().getHostname());
    }

    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution("/WEB-INF/jsp/info_job.jsp");
    }
}
